package com.arrogames.rgblabyrinth.storage {
	import flash.net.registerClassAlias;
	import flash.net.SharedObject;
	import org.as3commons.logging.api.ILogger;
	import org.as3commons.logging.api.getLogger;
	
	/**
	 * ...
	 * @author Robin van den Bogaard
	 */
	public class RGBStorage {
		
		private static const LOG:ILogger = getLogger(RGBStorage);
		
		private static const RGBSTORAGE:String = "RGBSTORAGE";
		private var soClient:SharedObject;
		
		private var profiles:Array;
		
		public function RGBStorage() {
			registerClassAlias("com.arrogames.rgblabyrinth.Profile", Profile);
			
			soClient = SharedObject.getLocal(RGBSTORAGE);
			if (!soClient.data.initiated) {
				initializeSharedObject();
			}
			
			readSharedObject();
		}
		
		public function addProfile(profile:Profile):void {
			profiles.push(profile);
			saveSharedObject();
		}
		
		public function hasProfile(name:String):Boolean {
			var found:Boolean = false;
			for (var i:int = 0; i < profiles.length && !found; i++) {
				var profile:Profile = profiles[i] as Profile;
				found = profile.name === name;
			}
			return found;
		}
		
		public function getProfile(name:String):Profile {
			var found:Boolean = false;
			var profile:Profile = null;
			for (var i:int = 0; i < profiles.length && !found; i++) {
				profile = profiles[i] as Profile;
				if (profile.name === name) {
					found = true;
				}
			}
			return profile;
		}
		
		private function initializeSharedObject():void {
			LOG.debug("Initalised new shared object");
			soClient.data.initiated = true;
			soClient.data.profiles = [];
			soClient.flush();
		}
		
		private function saveSharedObject():void {
			LOG.debug("Saving shared object");
			soClient.data.profiles = profiles;
			soClient.flush();
		}
		
		private function readSharedObject():void {
			LOG.debug("Loading shared object");
			profiles = soClient.data.profiles;
		}
		
	}

}